from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
import jwt


# 局部认证
class JWTQueryParamsAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # print(request.META)
        # 获取token
        token = request.META.get('HTTP_TOKEN')
        # print(token)
        if not token:
            raise AuthenticationFailed({"code": 401, "msg": "登录成功后才能访问"})
        # 切割
        # 解密payload，判断是否过期
        # 验证第三段的合法性
        salt = settings.SECRET_KEY
        try:
            # 从token中获取payload【不校验合法性】
            # unverified_payload = jwt.decode(token, None, False)
            # print(unverified_payload)
            # 从token中获取payload【校验合法性】
            payload = jwt.decode(jwt=token, key=salt, algorithms=["HS256"], verify=True)
            # print(payload)
            return payload, token
        except jwt.exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({"code": 401, "msg": "token已失效"})
        except jwt.exceptions.DecodeError:
            raise AuthenticationFailed({"code": 401, "msg": "token认证失败"})
        except jwt.exceptions.InvalidTokenError:
            raise AuthenticationFailed({"code": 401, "msg": "非法的token"})


# 签发token
def create_token(payload):
    salt = settings.SECRET_KEY
    # 构造Header，默认如下
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    jwt_token = jwt.encode(headers=headers, payload=payload, key=salt, algorithm='HS256')
    return jwt_token
